package com.avic.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.avic.gateway.common.constant.GatewayConstant;
import com.avic.gateway.common.util.ex.BizErrorCode;
import com.avic.gateway.model.GatewayResponse;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException;
import org.springframework.util.ReflectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 统一异常处理类
 *
 * @author: huangsheng
 * @date: 2018/8/24
 */
@Slf4j
public class GatewayErrorFilter extends AbstractZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        try {
            RequestContext context = RequestContext.getCurrentContext();
            ZuulException exception = this.findZuulException(context.getThrowable());
            log.error("进入系统异常拦截", exception);

            HttpServletResponse response = context.getResponse();
            response.setContentType(GatewayConstant.DEFAULT_RESPONSE_CONTENT_TYPE);
            response.setStatus(exception.nStatusCode);
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.print(JSONObject.toJSONString((GatewayResponse.initErrorResponse(BizErrorCode.SYSTEM_ERROR))));
            } catch (IOException e) {
                log.error("写入信息异常：{}", e.getMessage());
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
        } catch (Exception var5) {
            ReflectionUtils.rethrowRuntimeException(var5);
        }
        return null;
    }

    ZuulException findZuulException(Throwable throwable) {
        if (ZuulRuntimeException.class.isInstance(throwable.getCause())) {
            return (ZuulException) throwable.getCause().getCause();
        } else if (ZuulException.class.isInstance(throwable.getCause())) {
            return (ZuulException) throwable.getCause();
        } else {
            return ZuulException.class.isInstance(throwable) ? (ZuulException) throwable : new ZuulException(throwable, 500, (String) null);
        }
    }

}
